package com.crazymo.moskin.core;

import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import com.crazymo.replaceskin.MainActivity;

import java.util.Observable;

/**
 * @author : Crazy.Mo
 */
public class SkinManager extends Observable {
    private static SkinManager instance;
    /**
     * Activity生命周期回调
     */
    private MoActivityLifecycleCallbacks skinActivityLifecycle;
    private Application mContext;

    /**
     * 初始化 必须在Application中先进行初始化
     *
     * @param application
     */
    public static void init(Application application) {
        if (instance == null) {
            synchronized (SkinManager.class) {
                if (instance == null) {
                    instance = new SkinManager(application);
                }
            }
        }
    }

    public static SkinManager getInstance() {
        return instance;
    }


    private SkinManager(Application application) {
        mContext = application;
        //注册Activity生命周期
        skinActivityLifecycle = new MoActivityLifecycleCallbacks();
        mContext.registerActivityLifecycleCallbacks(skinActivityLifecycle);
    }

    /**
     * 更新皮肤 通知其他观察者
     */
    public void updateSkin(){
        setChanged();
        notifyObservers(null);
    }

    /**
     * 直接重启
     */
    public void restart(){
        Intent intent = new Intent(mContext, MainActivity.class);
        PendingIntent restartIntent = PendingIntent.getActivity(
                mContext.getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager mgr = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100,restartIntent);
        /** 1秒钟后重启应用 */
        /** 结束线程,一般与finishAll()一起使用 */
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}
